<template>
  <div class="m_container">
    <!-- 博客内容 -->
    <div class="m_content">
      <el-form
        ref="editForm"
        status-icon
        :model="editForm"
        :rules="rules1"
        label-width="5rem"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="首页图片" prop="firstPicture">
          <Upload :firstPicture="editForm.firstPicture" @change="imgChange"></Upload>
        </el-form-item>
 
        <el-form-item label="文章标签">
          <!-- <el-input v-model="oldtags" placeholder="请选择标签，多个标签请用逗号隔开" width="80%"></el-input> -->
          <el-tag
            :key="index"
            v-for="(tag, index) in editForm.tags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            style="width: 30%; margin-left: .625rem"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button
            v-else
            class="button-new-tag"
            style="margin-left: .625rem"
            size="small"
            @click="showInput"
            >+ New Tag</el-button
          >
        </el-form-item>

        <el-form-item label="文章分类" prop="categoryId">
          <el-select v-model="editForm.categoryId " placeholder="请选择分类专栏">
            <el-option
              v-for="item in categorys"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button
            type="primary"
            size="small"
            @click="dialog2 = true"
            style="margin-left: .625rem"
            >新建分类专栏</el-button
          >
        </el-form-item>
        <!-- <el-form-item label="文章类型" prop="flag">
          <el-select
            v-model="editForm.flag"
            placeholder="请选择文章类型，默认为原创"
          >
            <el-option label="原创" value="原创"></el-option>
            <el-option label="转载" value="转载"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="发布形式" prop="published">
          <el-select
            v-model="editForm.published"
            
            placeholder="请选择发布形式，默认为私密"
          >
            <el-option label="私密" :value="0"></el-option>
            <el-option label="公开" :value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <mavon-editor
            v-model="editForm.content"
            :placeholder="'Edit ···'"
            ref="md"
            @imgAdd="$imgAdd"
            @imgDel="$imgDel"
            @change="change"
            :toolbars="toolbars"
            :toolbarsBackground="'#f9f9f9'"
            :ishljs="true"
            style="height: calc(100vh - 3.125rem)"
          />
        </el-form-item>
        <el-form-item style="margin: auto">
          <el-button type="primary" @click="submitForm('editForm')"
            >保存发布</el-button
          >
          <el-button type="primary" @click="tempSave('editForm')"
            >保存草稿</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 新建分类专栏 -->
    <el-dialog title="新建分类专栏" :visible.sync="dialog2" width="30%">
      <el-form
        status-icon
        :model="type"
        ref="type"
        :rules="rules2"
        label-width="7.5rem"
      >
        <el-form-item label="分类专栏名" prop="name">
          <el-input
            v-model="type.name"
            placeholder="请输入要新建的分类专栏名"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog2 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('type')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  <script>
import Upload from './components/Upload.vue';
export default {
  components: { Upload },
  name: "EditBlog",
  data() {
    return {
      // id:'',
      mytest: "",
      editForm: {
        //博客文章表单
        id: null,
        title: "",
        description: "",
        first_picture: "",
        content: "",
        published: 1,
        tags: [],
        category: "",
        categoryId: 0,
      }, 

      oldtags: "", //字符串类型的标签
      type: {
        //分类专栏
        name: "",
      },
      //参数
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: false, // 全屏编辑
        readmodel: false, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: false, // 预览
      },
      categorys: [], // 所有分类专栏
      dialogFormVisible: false, //控制发布博客对话框
      dialog2: false, //控制新增分类专栏对话框
      rules1: {
        //表单校验
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 3,
            max: 100,
            message: "长度在 3 到 100 个字符",
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "请输入摘要", trigger: "blur" },
        ],
        first_picture: [
          { required: true, message: "请输入图片地址", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入文章内容", trigger: "blur" },
        ],
        type_id: [
          { required: true, message: "分类专栏不能为空", trigger: "blur" },
        ],
        flag: [
          { required: true, message: "文章类型不能为空", trigger: "blur" },
        ],
        published: [
          { required: true, message: "发布形式不能为空", trigger: "blur" },
        ],
      },
      rules2: {
        //表单校验
        name: [
          { required: true, message: "分类专栏名不能为空", trigger: "blur" },
        ],
      },
      formLabelWidth: "7.5rem", // 输入框的宽度
      inputVisible: false,
      inputValue: "",
      btags: [],
      tblogTags: [],
    };
  },
  props: ["id"],
  mounted() {
    this.initBlog();
    this.initCategory();
  },
  methods: {
    imgChange(url){
      this.editForm.firstPicture=url;
    },
    handleClose(tag) {
      this.editForm.tags.splice(this.editForm.tags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.editForm.tags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    //初始化博客数据
    initBlog() {
      const _this = this;
      console.log(this.id);
      this.getRequest("/api/article/common/getArticleById?id=" + this.id).then(
        (resp) => {
          _this.editForm = resp.data;
          // _this.editForm.tblogTags = resp.obj.tblogTags
        }
      );
    },
    //初始化分类
    initCategory() {
      const _this = this;
      this.getRequest("/api/category/admin/list").then((resp) => {
        _this.categorys = resp.data;
      });
    },
    //添加新的分类专栏
    addNewType() {
      const _this = this;
      this.postRequest("/api/type/saveType", this.type).then((resp) => {
        if (resp) {
          _this.type.name = "";
          this.initType();
          _this.dialog2 = false;
        }
      });
    },
    //校验添加分类专栏表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addNewType();
        } else {
          return false;
        }
      });
    },
    //校验博客基本内容表单
    submitForm(formName) {
      const _this = this;
      this.editForm.shareStatement = 1;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //发布博客
          this.postRequest(
            "/api/article/admin/saveOrUpdate",
            this.editForm
          ).then((resp) => {
            if (resp) {
              _this.$router.push("/blog/allblogs");
            }
          });
        } else {
          return false;
        }
      });
    },
    // 保存草稿
    tempSave(formName) {
      const _this = this;
      this.editForm.shareStatement = 0;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //发布博客
          this.postRequest(
            "/api/article/admin/saveOrUpdate",
            this.editForm
          ).then((resp) => {
            if (resp) {
              _this.$router.push("/blog/allblogs");
            }
          });
        } else {
          return false;
        }
      });
    },
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append("image", $file);
      this.img_file[pos] = $file;
      this.postRequest("/api/edit/uploadimg", this.img_file[pos]).then(
        (res) => {
          let _res = res.data;
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
          this.$refs.md.$img2Url(pos, _res.url);
        }
      );
    },
    $imgDel(pos) {
      delete this.img_file[pos];
    },
    change(value, render) {
      this.html = render;
    },
  },
};
</script>
  
  <style>
.m_container {
  margin-top: 1.25rem;
}
</style>
  
